/* GETCOURSE — CUSTOM SIDEBAR / v2.18 */
(function () {
    'use strict';

    /* CUSTOM LINKS */
    const CUSTOM_LINKS = {
        profile: '/my-profile',
        notifications: '/my-notifications',
        password: '/change-password',
        staff: '/staff',
        chatium: '/mobile-app',
        inbox: '/admin-messages'
    };

    const MOBILE_BREAKPOINT = 767;

    /* SYSTEM LINKS */
    const SYSTEM_LINKS = {
        profile: [
            '/user/my/profile'
        ],
        notifications: [
            '/pl/notifications/settings/my'
        ],
        password: [
            '/user/my/changePassword'
        ],
        chatium: [
            '/pl/chatium/school/enter'
        ]
    };

    /* PROFILE SUBMENU */
    const PROFILE_SUBMENU = {
        profile: {
            label: 'Профиль',
            texts: [
                'основное',
                'профиль',
                'мой профиль'
            ],
            className: 'gc-psych-custom-profile-subitem'
        },
        notifications: {
            texts: [
                'уведомления'
            ],
            className: 'gc-psych-custom-notifications-subitem'
        },
        password: {
            texts: [
                'сменить пароль'
            ],
            className: 'gc-psych-custom-password-subitem'
        }
    };

    /* ICONS */
    const ICONS = {
        cms: `
            <rect x="3" y="4" width="18" height="16" rx="2.5"/>
            <path d="M3 8h18"/>
            <path d="M7 6h.01M10 6h.01"/>
        `,
        teach: `
            <path d="M4 5.5A2.5 2.5 0 0 1 6.5 3H11v17H6.5A2.5 2.5 0 0 0 4 22z"/>
            <path d="M20 5.5A2.5 2.5 0 0 0 17.5 3H13v17h4.5A2.5 2.5 0 0 1 20 22z"/>
        `,
        user: `
            <circle cx="12" cy="8" r="3.5"/>
            <path d="M5 20a7 7 0 0 1 14 0"/>
        `,
        tasks: `
            <rect x="4" y="3" width="16" height="18" rx="2.5"/>
            <path d="M8 8h8M8 12h8M8 16h5"/>
        `,
        notifications: `
            <path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9"/>
            <path d="M10 21h4"/>
        `,
        sales: `
            <path d="M4 19V9M10 19V5M16 19v-7M22 19V3"/>
            <path d="M2 19h21"/>
        `,
        purchases: `
            <path d="M5 8h14l-1 13H6L5 8z"/>
            <path d="M9 10V6a3 3 0 0 1 6 0v4"/>
        `,
        chatium: `
            <rect x="4" y="3" width="16" height="18" rx="4"/>
            <path d="M9 7h6M9 11h6M9 15h3"/>
        `,
        marathon: `
            <path d="M13 2 5 13h6l-1 9 8-12h-6z"/>
        `
    };

    /* LABELS */
    const LABELS = {
        cms: 'Сайт',
        teach: 'Обучение',
        user: 'Ученики',
        tasks: 'CRM',
        notifications: 'Сообщения',
        chatium: 'Apps'
    };

    /* HELPERS */
    function normalizeText(value) {
        return String(value || '')
            .replace(/\s+/g, ' ')
            .trim()
            .toLowerCase();
    }

    function isMobile() {
        return window.innerWidth <= MOBILE_BREAKPOINT;
    }

    function getType(item) {
        const className = [...item.classList].find(
            className =>
                className.startsWith('menu-item-') &&
                className !== 'menu-item'
        );

        return className
            ? className.replace('menu-item-', '')
            : null;
    }

    function getPath(link) {
        try {
            return new URL(
                link.href,
                window.location.origin
            ).pathname;
        } catch (error) {
            return '';
        }
    }

    function getUrlInfo(value) {
        try {
            return new URL(
                value,
                window.location.origin
            );
        } catch (error) {
            return null;
        }
    }

    function isInboxUrl(value) {
        const url =
            getUrlInfo(
                value
            );

        if (!url) {
            return false;
        }

        if (
            url.pathname !==
            '/pl/tasks/resp'
        ) {
            return false;
        }

        return (
            url.searchParams.get(
                'filter[object_type_id]'
            ) === '55'
        );
    }

    function isInboxMenuEntry(item) {
        if (!item) {
            return false;
        }

        const label =
            normalizeText(
                item.label ||
                item.title ||
                item.name
            );

        return (
            label === 'входящие' ||
            isInboxUrl(
                item.url
            )
        );
    }

    function isCustomMessagesPage() {
        return (
            window.location.pathname ===
            CUSTOM_LINKS.inbox
        );
    }

    function forceCustomMessagesActiveSection() {
        if (!isCustomMessagesPage()) {
            return false;
        }

        const menu =
            document.querySelector(
                '#gcAccountUserMenu ' +
                '.gc-account-user-menu'
            );

        if (!menu) {
            return false;
        }

        const items =
            menu.querySelectorAll(
                ':scope > .menu-item'
            );

        let changed = false;

        items.forEach(item => {
            const shouldBeActive =
                item.classList.contains(
                    'menu-item-notifications'
                );

            if (
                item.classList.contains(
                    'active'
                ) !== shouldBeActive
            ) {
                item.classList.toggle(
                    'active',
                    shouldBeActive
                );

                changed = true;
            }
        });

        return changed;
    }

    /*
     * GetCourse хранит URL пунктов меню не только в DOM,
     * но и в window.gcAccountUserMenu.
     * Для пункта "Приложение" патчим и исходную модель,
     * иначе повторный клик может открыть системную страницу.
     */
    function patchNativeMenuConfig() {
        const items =
            window.gcAccountUserMenu?.items;

        if (!Array.isArray(items)) {
            return false;
        }

        let changed = false;

        function walk(list) {
            if (!Array.isArray(list)) {
                return;
            }

            list.forEach(item => {
                if (!item) {
                    return;
                }

                if (
                    item.id === 'chatium_app' &&
                    item.url !== CUSTOM_LINKS.chatium
                ) {
                    item.url =
                        CUSTOM_LINKS.chatium;

                    changed = true;
                }

                if (
                    isInboxMenuEntry(
                        item
                    ) &&
                    item.url !==
                        CUSTOM_LINKS.inbox
                ) {
                    item.url =
                        CUSTOM_LINKS.inbox;

                    changed = true;
                }

                walk(item.subitems);
            });
        }

        walk(items);

        return changed;
    }

    function getCustomUrlBySystemPath(path) {
        for (const type of Object.keys(SYSTEM_LINKS)) {
            if (
                SYSTEM_LINKS[type].includes(path) &&
                CUSTOM_LINKS[type]
            ) {
                return CUSTOM_LINKS[type];
            }
        }

        return null;
    }

    function matchesSystemLink(link, type) {
        const paths =
            SYSTEM_LINKS[type] || [];

        return paths.includes(
            getPath(link)
        );
    }

    function matchesSubmenuLink(link, type) {
        const config =
            PROFILE_SUBMENU[type];

        if (!config) {
            return false;
        }

        if (
            matchesSystemLink(
                link,
                type
            )
        ) {
            return true;
        }

        const text =
            normalizeText(
                link.textContent
            );

        return config.texts.includes(
            text
        );
    }

    /* NATIVE GETCOURSE MENU */
    function getNativeMenuItem(id) {
        const items =
            window.gcAccountUserMenu?.items;

        if (!Array.isArray(items)) {
            return null;
        }

        return (
            items.find(
                item => item.id === id
            ) || null
        );
    }

    function getMenuLabel(type) {
        if (type !== 'sales') {
            return LABELS[type] || '';
        }

        return (
            getNativeMenuItem(
                'sales'
            )?.label || ''
        );
    }

    function getMenuIconType(type) {
        if (type !== 'sales') {
            return type;
        }

        const label =
            getNativeMenuItem(
                'sales'
            )?.label
                ?.trim()
                .toLowerCase();

        if (label === 'покупки') {
            return 'purchases';
        }

        if (label === 'продажи') {
            return 'sales';
        }

        return null;
    }

    /* SVG */
    function makeSvg(type) {
        const body =
            ICONS[type];

        if (!body) {
            return null;
        }

        const wrapper =
            document.createElement(
                'span'
            );

        wrapper.innerHTML = `
            <svg
                class="gc-psych-menu-icon"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="1.8"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
            >
                ${body}
            </svg>
        `;

        return wrapper.firstElementChild;
    }

    /* LABEL */
    function setLabel(link, text) {
        if (!text) {
            return;
        }

        link.classList.add(
            'with-label'
        );

        let label =
            link.querySelector(
                ':scope > .menu-item-label'
            );

        if (!label) {
            label =
                document.createElement(
                    'span'
                );

            label.className =
                'menu-item-label';

            link.appendChild(
                label
            );
        }

        if (
            label.textContent !==
            text
        ) {
            label.textContent =
                text;
        }

        const badge =
            link.querySelector(
                ':scope > .notify-count'
            );

        if (badge) {
            badge.classList.add(
                'with-label'
            );
        }
    }

    /* PROFILE ROOT ITEM */
    function enhanceProfile(item, link) {
        const userName =
            window.accountSafeUserName ||
            'Профиль';

        setLabel(
            link,
            userName
        );

        item.classList.remove(
            'gc-custom-profile-link'
        );

        const href =
            link.getAttribute(
                'href'
            ) || '';

        if (
            href === CUSTOM_LINKS.profile ||
            href ===
                window.location.origin +
                CUSTOM_LINKS.profile
        ) {
            link.setAttribute(
                'href',
                'javascript:void(0)'
            );
        }
    }

    /* STANDARD MENU ITEM */
    function enhanceStandardItem(
        item,
        link,
        type
    ) {
        const iconType =
            getMenuIconType(
                type
            );

        if (
            type === 'sales' &&
            !iconType
        ) {
            return false;
        }

        let existingSvg =
            link.querySelector(
                ':scope > .gc-psych-menu-icon'
            );

        if (
            existingSvg &&
            existingSvg.dataset.psychIconType !==
                iconType
        ) {
            existingSvg.remove();
            existingSvg = null;
        }

        if (!existingSvg) {
            const svg =
                makeSvg(
                    iconType
                );

            if (svg) {
                svg.dataset.psychIconType =
                    iconType;

                const originalImage =
                    link.querySelector(
                        ':scope > .menu-item-icon'
                    );

                if (originalImage) {
                    originalImage.insertAdjacentElement(
                        'afterend',
                        svg
                    );
                } else {
                    link.prepend(
                        svg
                    );
                }
            }
        }

        const label =
            getMenuLabel(
                type
            );

        if (label) {
            setLabel(
                link,
                label
            );
        }

        return true;
    }

    /* MENU ITEM */
    function enhanceItem(item) {
        const type =
            getType(
                item
            );

        const link =
            item.querySelector(
                ':scope > a'
            );

        if (
            !type ||
            !link
        ) {
            return false;
        }

        item.classList.add(
            'gc-psych-menu-item'
        );

        if (type === 'profile') {
            enhanceProfile(
                item,
                link
            );

            return true;
        }

        return enhanceStandardItem(
            item,
            link,
            type
        );
    }

    /* MAIN MENU */
    function enhanceMenu() {
        const root =
            document.querySelector(
                '#gcAccountUserMenu'
            );

        if (!root) {
            return false;
        }

        const menu =
            root.querySelector(
                '.gc-account-user-menu'
            );

        const leftbar =
            root.querySelector(
                '.gc-account-leftbar'
            );

        if (
            !menu ||
            !leftbar
        ) {
            return false;
        }

        const salesItem =
            menu.querySelector(
                ':scope > .menu-item-sales'
            );

        if (
            salesItem &&
            !getNativeMenuItem(
                'sales'
            )
        ) {
            leftbar.classList.remove(
                'gc-psych-leftbar'
            );

            return false;
        }

        menu
            .querySelectorAll(
                ':scope > .menu-item'
            )
            .forEach(
                enhanceItem
            );

        leftbar.classList.add(
            'gc-psych-leftbar'
        );

        return true;
    }

    /* INBOX LINK */
    function patchInboxLinks() {
        const root =
            document.querySelector(
                '#gcAccountUserMenu'
            );

        if (!root) {
            return false;
        }

        let changed = false;

        root.querySelectorAll('a')
            .forEach(link => {
                const text =
                    normalizeText(
                        link.textContent
                    );

                const href =
                    link.getAttribute(
                        'href'
                    ) || '';

                if (
                    text !== 'входящие' &&
                    !isInboxUrl(href)
                ) {
                    return;
                }

                if (
                    href !==
                    CUSTOM_LINKS.inbox
                ) {
                    link.setAttribute(
                        'href',
                        CUSTOM_LINKS.inbox
                    );

                    changed = true;
                }

                link.classList.add(
                    'gc-psych-custom-inbox-link'
                );
            });

        return changed;
    }

    /* PROFILE SUBMENU LINK */
    function patchProfileSubmenuLink(
        links,
        type
    ) {
        const config =
            PROFILE_SUBMENU[type];

        const customUrl =
            CUSTOM_LINKS[type];

        if (
            !config ||
            !customUrl
        ) {
            return false;
        }

        const link =
            links.find(
                item =>
                    matchesSubmenuLink(
                        item,
                        type
                    )
            );

        if (!link) {
            return false;
        }

        if (
            link.getAttribute(
                'href'
            ) !== customUrl
        ) {
            link.setAttribute(
                'href',
                customUrl
            );
        }

        if (
            config.label &&
            link.textContent.trim() !==
                config.label
        ) {
            link.textContent =
                config.label;
        }

        if (config.className) {
            link.classList.add(
                config.className
            );
        }

        return true;
    }

    /* PROFILE SUBMENU */
    function enhanceProfileSubmenu() {
        const submenu =
            document.querySelector(
                '#gcAccountUserMenu .gc-account-user-submenu-bar'
            );

        if (!submenu) {
            return false;
        }

        const links = [
            ...submenu.querySelectorAll(
                '.gc-account-user-submenu .subitem-link'
            )
        ];

        if (!links.length) {
            return false;
        }

        patchProfileSubmenuLink(
            links,
            'profile'
        );

        patchProfileSubmenuLink(
            links,
            'notifications'
        );

        patchProfileSubmenuLink(
            links,
            'password'
        );

        return true;
    }

    /* MOBILE SUBMENU */
    function enhanceMobileSubmenu() {
        if (!isMobile()) {
            return false;
        }

        const submenu =
            document.querySelector(
                '#gcAccountUserMenu .gc-account-user-submenu-bar'
            );

        if (!submenu) {
            return false;
        }

        let mobileHeader =
            submenu.querySelector(
                ':scope > .gc-psych-submenu-mobile-header'
            );

        if (!mobileHeader) {
            mobileHeader =
                document.createElement(
                    'div'
                );

            mobileHeader.className =
                'gc-psych-submenu-mobile-header';

            const backButton =
                document.createElement(
                    'button'
                );

            backButton.type =
                'button';

            backButton.className =
                'gc-psych-submenu-back';

            backButton.setAttribute(
                'aria-label',
                'Вернуться в основное меню'
            );

            const title =
                document.createElement(
                    'span'
                );

            title.className =
                'gc-psych-submenu-mobile-title';

            mobileHeader.appendChild(
                backButton
            );

            mobileHeader.appendChild(
                title
            );

            submenu.prepend(
                mobileHeader
            );

            backButton.addEventListener(
                'click',
                function (event) {
                    event.preventDefault();
                    event.stopPropagation();

                    submenu.style.setProperty(
                        'display',
                        'none',
                        'important'
                    );

                    const mainMenu =
                        document.querySelector(
                            '#gcAccountUserMenu .gc-account-user-menu'
                        );

                    if (mainMenu) {
                        mainMenu.style.removeProperty(
                            'display'
                        );
                    }

                    [
                        ...submenu.classList
                    ].forEach(
                        className => {
                            if (
                                className.startsWith(
                                    'gc-account-user-submenu-bar-'
                                )
                            ) {
                                submenu.classList.remove(
                                    className
                                );
                            }
                        }
                    );
                }
            );
        }

        const systemTitle =
            submenu.querySelector(
                ':scope > div:not(.gc-psych-submenu-mobile-header) h3'
            );

        const mobileTitle =
            mobileHeader.querySelector(
                '.gc-psych-submenu-mobile-title'
            );

        if (
            systemTitle &&
            mobileTitle
        ) {
            mobileTitle.textContent =
                systemTitle.textContent.trim();
        }

        return true;
    }

    /* SYSTEM LINK PATCH */
    function patchSystemLinks(
        root = document
    ) {
        patchNativeMenuConfig();

        root
            .querySelectorAll(
                'a[href]'
            )
            .forEach(link => {
                if (
                    link.matches(
                        '#gcAccountUserMenu .gc-account-user-menu > .menu-item-profile > a'
                    )
                ) {
                    return;
                }

                const url =
                    getUrlInfo(
                        link.getAttribute(
                            'href'
                        ) || link.href
                    );

                if (!url) {
                    return;
                }

                /*
                 * Не подменяем служебный Chatium QR-пункт
                 * вида /pl/chatium/school/enter?path=...
                 * Подменяем только обычный пункт "Приложение".
                 */
                if (
                    url.pathname ===
                        '/pl/chatium/school/enter' &&
                    url.search
                ) {
                    return;
                }

                const customUrl =
                    getCustomUrlBySystemPath(
                        url.pathname
                    );

                if (!customUrl) {
                    return;
                }

                if (
                    link.getAttribute(
                        'href'
                    ) !== customUrl
                ) {
                    link.setAttribute(
                        'href',
                        customUrl
                    );
                }
            });
    }

    /* SYSTEM LINK REDIRECT */
    function enableSystemLinkRedirect() {
        document.addEventListener(
            'click',
            function (event) {
                const link =
                    event.target.closest(
                        'a[href]'
                    );

                if (!link) {
                    return;
                }

                if (
                    link.matches(
                        '#gcAccountUserMenu .gc-account-user-menu > .menu-item-profile > a'
                    )
                ) {
                    return;
                }

                patchNativeMenuConfig();

                const url =
                    getUrlInfo(
                        link.getAttribute(
                            'href'
                        ) || link.href
                    );

                if (!url) {
                    return;
                }

                if (
                    url.pathname ===
                        '/pl/chatium/school/enter' &&
                    url.search
                ) {
                    return;
                }

                const customUrl =
                    getCustomUrlBySystemPath(
                        url.pathname
                    );

                if (!customUrl) {
                    return;
                }

                event.preventDefault();
                event.stopPropagation();
                event.stopImmediatePropagation();

                window.location.href =
                    customUrl;
            },
            true
        );
    }

    /* STAFF LINK */
    function patchStaffLinks(
        root = document
    ) {
        root
            .querySelectorAll(
                '.standard-page-menu a[href]'
            )
            .forEach(link => {
                const text =
                    normalizeText(
                        link.textContent
                    );

                if (
                    text !==
                    'сотрудники'
                ) {
                    return;
                }

                link.setAttribute(
                    'href',
                    CUSTOM_LINKS.staff
                );

                link.dataset.psychStaffLink =
                    '1';
            });
    }

    /* SUBMENUS */
    function enhanceSubmenus() {
        enhanceProfileSubmenu();
        enhanceMobileSubmenu();
        patchSystemLinks();
    }

    /* MENU CLICK */
    function enableMenuHandling() {
        document.addEventListener(
            'click',
            function (event) {
                const menuLink =
                    event.target.closest(
                        '#gcAccountUserMenu .gc-account-user-menu > .menu-item > a'
                    );

                if (!menuLink) {
                    return;
                }

                [
                    50,
                    150,
                    300,
                    600
                ].forEach(
                    delay => {
                        window.setTimeout(
                            function () {
                                enhanceMenu();
                                patchInboxLinks();
                                forceCustomMessagesActiveSection();
                                enhanceSubmenus();
                            },
                            delay
                        );
                    }
                );
            }
        );
    }

    /* RESIZE */
    function enableResizeHandling() {
        let resizeTimer =
            null;

        window.addEventListener(
            'resize',
            function () {
                window.clearTimeout(
                    resizeTimer
                );

                resizeTimer =
                    window.setTimeout(
                        function () {
                            enhanceMenu();
                            forceCustomMessagesActiveSection();
                            enhanceSubmenus();
                        },
                        150
                    );
            }
        );
    }

    /* DYNAMIC CONTENT */
    function enableDynamicHandling() {
        let patchTimer =
            null;

        function schedulePatch() {
            window.clearTimeout(
                patchTimer
            );

            patchTimer =
                window.setTimeout(
                    function () {
                        patchSystemLinks();
                        patchInboxLinks();
                        forceCustomMessagesActiveSection();
                        patchStaffLinks();
                        enhanceProfileSubmenu();
                    },
                    30
                );
        }

        const observer =
            new MutationObserver(
                function (mutations) {
                    const shouldPatch =
                        mutations.some(
                            mutation =>
                                mutation.type ===
                                    'childList' ||
                                (
                                    mutation.type ===
                                        'attributes' &&
                                    mutation.attributeName ===
                                        'href'
                                )
                        );

                    if (shouldPatch) {
                        schedulePatch();
                    }
                }
            );

        observer.observe(
            document.body,
            {
                childList: true,
                subtree: true,
                attributes: true,
                attributeFilter: [
                    'href'
                ]
            }
        );
    }


    /* FIREFOX ANDROID — VISUAL VIEWPORT FIX */
    function isFirefoxAndroid() {
        const ua =
            navigator.userAgent || '';

        return (
            /Android/i.test(ua) &&
            /Firefox/i.test(ua)
        );
    }

    function getFirefoxActionsTarget() {
        return document.querySelector(
            '#gcAccountUserMenu ' +
            '.gc-page-nav-items-menu ' +
            '> .toggler-item'
        );
    }

    function updateFirefoxFixedControls() {
        if (
            !isMobile() ||
            !isFirefoxAndroid()
        ) {
            return;
        }

        document.documentElement
            .classList.add(
                'gc-psych-firefox-android'
            );

        const viewport =
            window.visualViewport;

        const viewportHeight =
            viewport
                ? viewport.height
                : window.innerHeight;

        const viewportOffsetTop =
            viewport
                ? viewport.offsetTop
                : 0;

        const viewportWidth =
            viewport
                ? viewport.width
                : window.innerWidth;

        const bottomGap =
            16;

        const burger =
            document.querySelector(
                '#gcAccountUserMenu ' +
                '.gc-account-leftbar' +
                '.gc-psych-leftbar'
            );

        if (
            burger &&
            !burger.classList.contains(
                'expanded'
            )
        ) {
            const burgerHeight =
                burger.getBoundingClientRect()
                    .height || 44;

            const burgerTop =
                viewportOffsetTop +
                viewportHeight -
                burgerHeight -
                bottomGap;

            burger.style.setProperty(
                '--gc-firefox-fixed-top',
                `${Math.max(0, burgerTop)}px`
            );
        }

        const actions =
            getFirefoxActionsTarget();

        if (actions) {
            const actionsHeight =
                actions.getBoundingClientRect()
                    .height || 44;

            const actionsTop =
                viewportOffsetTop +
                viewportHeight -
                actionsHeight -
                bottomGap;

            actions.style.setProperty(
                '--gc-firefox-fixed-top',
                `${Math.max(0, actionsTop)}px`
            );
        }

    }

    function enableFirefoxFixedControlsFix() {
        if (!isFirefoxAndroid()) {
            return;
        }

        let rafId =
            null;

        function scheduleUpdate() {
            if (rafId !== null) {
                return;
            }

            rafId =
                window.requestAnimationFrame(
                    function () {
                        rafId =
                            null;

                        updateFirefoxFixedControls();
                    }
                );
        }

        window.addEventListener(
            'scroll',
            scheduleUpdate,
            {
                passive: true
            }
        );

        window.addEventListener(
            'resize',
            scheduleUpdate,
            {
                passive: true
            }
        );

        if (window.visualViewport) {
            window.visualViewport
                .addEventListener(
                    'scroll',
                    scheduleUpdate,
                    {
                        passive: true
                    }
                );

            window.visualViewport
                .addEventListener(
                    'resize',
                    scheduleUpdate,
                    {
                        passive: true
                    }
                );
        }

        const observer =
            new MutationObserver(
                scheduleUpdate
            );

        observer.observe(
            document.body,
            {
                childList: true,
                subtree: true
            }
        );

        scheduleUpdate();

        [
            50,
            150,
            300,
            800,
            1500
        ].forEach(
            delay => {
                window.setTimeout(
                    scheduleUpdate,
                    delay
                );
            }
        );
    }

    /* INIT */
    function init() {
        patchNativeMenuConfig();

        enableMenuHandling();
        enableResizeHandling();
        enableDynamicHandling();
        enableSystemLinkRedirect();
        enableFirefoxFixedControlsFix();

        enhanceMenu();
        patchInboxLinks();
        forceCustomMessagesActiveSection();
        enhanceSubmenus();
        patchStaffLinks();

        [
            50,
            150,
            300,
            800,
            1500,
            3000
        ].forEach(
            delay => {
                window.setTimeout(
                    function () {
                        patchNativeMenuConfig();
                        enhanceMenu();
                        patchInboxLinks();
                        forceCustomMessagesActiveSection();
                        enhanceSubmenus();
                        patchStaffLinks();
                    },
                    delay
                );
            }
        );
    }

    /* START */
    if (
        document.readyState ===
        'loading'
    ) {
        document.addEventListener(
            'DOMContentLoaded',
            init,
            {
                once: true
            }
        );
    } else {
        init();
    }
})();
